package com.woniu.car.advice;

import com.woniu.car.config.ElasticSearchServerEntity;
import com.woniu.car.config.ElasticSearchShopEntity;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.math.BigDecimal;

@Aspect
@Component
public class AdviceConfig {
    @Autowired
    private ElasticsearchRestTemplate template;

    /**
     * 
     * @param jp
     * @throws Exception
     * 新增商店的时候增加这个注解可以索引库新增.
     */
    @After("@annotation(com.woniu.car.annotation.ElasticSearchShopAdd)")
    public void ElasticSearchShopAdd(JoinPoint jp) throws Exception {
        Object obj = jp.getArgs()[0];
        ElasticSearchShopEntity entity = new ElasticSearchShopEntity();
        //shopId
        Field field1 = obj.getClass().getDeclaredFields()[0];
        //经度
        Field field2 = obj.getClass().getDeclaredFields()[4];
        //纬度
        Field field3 = obj.getClass().getDeclaredFields()[5];
        field1.setAccessible(true);
        field2.setAccessible(true);
        field3.setAccessible(true);
        BeanUtils.copyProperties(obj,entity);
        entity.setLongitudeAndShopLatitude(
                String.valueOf((BigDecimal) field2.get(obj))+ ","+
                String.valueOf((BigDecimal) field3.get(obj)));
        entity.setId((String) field1.get(obj));
        template.save(entity);
    }
    @After("@annotation(com.woniu.car.annotation.ElasticSearchShopAdd)")
    public void ElasticSearchServerAdd(JoinPoint jp) throws Exception {
        Object obj = jp.getArgs()[0];
        ElasticSearchServerEntity entity = new ElasticSearchServerEntity();
        Field field = obj.getClass().getDeclaredFields()[0];
        field.setAccessible(true);
        String Id = (String) field.get(obj);
        BeanUtils.copyProperties(obj,entity);
        entity.setId(Id);
        template.save(entity);
    }
}
